package com.kevin.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kevin.common.util.IpUtil;
import com.kevin.common.util.tree.RequestUtil;
import com.kevin.service.entity.SysLogLogin;
import com.kevin.service.mapper.SysLogLoginMapper;
import com.kevin.service.service.SysLogLoginService;
import lombok.RequiredArgsConstructor;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 登录日志(SysLogLogin)表服务实现类
 *
 * @author makejava
 * @since 2023-03-30 14:38:35
 */
@Service
@RequiredArgsConstructor
public class SysLogLoginServiceImpl extends ServiceImpl<SysLogLoginMapper, SysLogLogin> implements SysLogLoginService {

    private final Ip2regionSearcher ip2regionSearcher;

    @Override
    public void save(String username, Integer status, Integer operation) {
        HttpServletRequest request = RequestUtil.getRequest();
        assert request != null;
        String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
        String ip = IpUtil.getClientIP(request);
        String address = ip2regionSearcher.getAddress(ip);
        SysLogLogin entity = new SysLogLogin();
        entity.setUsername(username);
        entity.setStatus(status);
        entity.setOperation(operation);
        entity.setIp(ip);
        entity.setAddress(address);
        entity.setUserAgent(userAgent);
        entity.setCreateTime(new Date());

        baseMapper.insert(entity);
    }
}

